const P_NUM = 10;
const ACTION = ['All in', 'Call', 'Fold'];
const SUITS = ['red diam', 'red heart', 'black club', 'black spade'];
const FACES = ['A', 'K', 'Q', 'J', '10', '9', '8', '7', '6', '5', '4', '3', '2'];
const PLAYER_NAMES = ['Atlanta', 'Virtuoso', 'Kaizan', 'Silvan', 'Nico', 'PaunchBoy', 'Play4real', 'gsvette', 'kanstrup2', 'Seat'];
const TABLE_SUITS = ['d', 'h', 'c', 's'];
const USER_NUM = 7;
const CALL = 11.75;
const SBLIND = 2.0;
const BBLIND = 4.0;

var usedCards = [];
var eliminatedPlayers = [];
var playersOrder = [1,2,3,4,5,6,7,8,9,10];
var roundNum;
var userTurn = false;

function newGame()
{
	runPreFlop();
	setTimeout('runFlop()', 22000);
	action = -1;
	roundNum = 1;
	
	for(var position in playersOrder) {
		player = playersOrder[position];
		if(player == USER_NUM) {
			setTimeout('changeTurn('+ player +')',  22000 + 2000 * position);
			break;
		}
		setTimeout('chooseActionForUser('+ player +',' + action + ')', 22000 + 2000 * position);
	}
	
}	

function logUserAction(user, action) 
{
	var chat = document.getElementById("chat messages");
	message = "<li><h3>" + user + "</h3><p>" + action + "</p></li>"
	console.log(message);
	chat.innerHTML = message + chat.innerHTML;
}

function continueGame()
{
	if(roundNum == 1) {
		var user_position = playersOrder.indexOf(USER_NUM);
		for(var position in playersOrder) {
			if(position > user_position) {
				player = playersOrder[position];
				console.log(player);
				setTimeout('chooseActionForUser('+ player +',' + action + ')', 2000 * (position - user_position));
			}
		}
		timeout = 2000 * (playersOrder.length - user_position);
		setTimeout('runTurn()', timeout);
		action = -1;
		timeout = timeout + 2000;
		
		for(var position in playersOrder) {
			player = playersOrder[position];
			if(player == USER_NUM) {
				setTimeout('changeTurn('+ player +')', timeout + 2000 * position);
				break;
			}
			setTimeout('chooseActionForUser('+ player +',' + action + ')', timeout + 2000 * position);
		}
		roundNum = 2;
		
	 } else if(roundNum == 2) {
		var user_position = playersOrder.indexOf(USER_NUM);
		for(var position in playersOrder) {
			if(position > user_position) {
				player = playersOrder[position];
				console.log(player);
				setTimeout('chooseActionForUser('+ player +',' + action + ')', 2000 * (position - user_position));
			}
		}
		timeout = 2000 * (playersOrder.length - user_position);
		setTimeout('runRiver()', timeout);
		action = -1;
		timeout = timeout + 2000;
		
		for(var position in playersOrder) {
			player = playersOrder[position];
			if(player == USER_NUM) {
				setTimeout('changeTurn('+ player +')', timeout + 2000 * position);
				break;
			}
			setTimeout('chooseActionForUser('+ player +',' + action + ')', timeout + 2000 * position);
		}
	
		roundNum = 3;
	} else if(roundNum == 3) {
		var user_position = playersOrder.indexOf(USER_NUM);
		for(var position in playersOrder) {
			if(position > user_position) {
				player = playersOrder[position];
				console.log(player);
				setTimeout('chooseActionForUser('+ player +',' + action + ')', 2000 * (position - user_position));
			}
		}
		
		//setTimeout('changeTurn(7)', 8000);
		timeout = 2000 * (playersOrder.length - user_position);
		setTimeout('setWinner()', timeout);
	}
}


function setWinner()
{
	var table = document.getElementById("table");	
	var liCollection = table.getElementsByTagName("li");
	var tableFaces = [];
	var tableSuits = [];
	var usersRank = [];
	var winnerNum = 0;
	var winnerRank = 0;
	
    for (i = 0; i < liCollection.length; i++) {
		if(liCollection[i].getAttribute("class").substring(0,4) == "card") {
			card = liCollection[i].getAttribute("class");
			suit = card.charAt(5);
			if(suit == 'd') suit = 'red diam';
			else if(suit == 'h') suit = 'red heart';
			else if(suit == 'c') suit = 'black club';
			else suit = 'black spade';
			
			face = (card.length > 8) ? card.substring(7,9) : card.charAt(7);
			
			tableFaces[tableFaces.length] = face.toUpperCase();
			tableSuits[tableSuits.length] = suit;
		}
	}
				
	console.log(tableFaces);
	console.log(tableSuits);
	
	for(i = 1; i <= 10; i++) {
		if(!arrayContains(eliminatedPlayers, i)) {
			var userFaces = [];
			var userSuits = [];
			var user = document.getElementById("user-" + i);
			var bCollection = user.getElementsByTagName("b");

			userSuits[tableSuits.length] = bCollection[0].className;
			userSuits[tableSuits.length] = bCollection[1].className;
		
			userFaces[tableFaces.length] = bCollection[0].innerHTML;
			userFaces[tableFaces.length] = bCollection[1].innerHTML;
			temp = combinationWeight(tableSuits.concat(userSuits), tableFaces.concat(userFaces))
			console.log	('player-' + i + ' rank-' + temp);
			if(temp > winnerRank) {
				winnerRank = temp;
				winnerNum = i;
			}
		}
	}
	
	var combination;
	switch(winnerRank) {
		case 200:
			combination = "Royal Flush";
			break;
		case 190:
			combination = "Straight Flush";
			break;
		case 180:
			combination = "Four of a Kind";
			break;
		case 170:
			combination = "Full House";
			break;
		case 160:
			combination = "Flush";
			break;
		case 150:
			combination = "Straight";
			break;
		case 140:
			combination = "Three of a Kind";
			break;
		case 130:
			combination = "Two Pair";
			break;
		case 120:
			combination = "One Pair";
			break;
		default:
			combination = "High Card";
	}
	
	
	var element = document.getElementById("winner");
	element.innerHTML = PLAYER_NAMES[winnerNum - 1];
	logUserAction("System", "Winner " + PLAYER_NAMES[winnerNum - 1] + " with combination " + combination);
}

function changeTurn(currentUsr)
{
	var element;
	for(i = 1; i <= P_NUM; i++) {
		element = document.getElementById("user-" + i);
		if(element) element.className = "user-" + i;
	}
	userTurn = (currentUsr == USER_NUM); 
	element = document.getElementById("user-" + currentUsr);
	element.className = "user-" + currentUsr + " active";
	
	
}

function changeTableCard()
{
	var element = document.getElementById("table");
	chooseCardForTable(element);
}

function reset()
{
	for(i = 1; i <= P_NUM; i++) {
		var element = document.getElementById("user-" + i);
		if(element) element.className = "user-" + i;
	}
}

function chooseActionForUser(userNum, action)
{
	changeTurn(userNum);
	if(!arrayContains(eliminatedPlayers, userNum)) {
		var user = document.getElementById("user-" + userNum);
		var spanCollection = user.getElementsByTagName("span");
		for (i = 0; i < spanCollection.length; i++) {
			if(spanCollection[i].getAttribute("class") == "status") {
				spanCollection[i].innerHTML = (action == - 1) ? ACTION[Math.floor(Math.random()*3)] : action;
				if(spanCollection[i].innerHTML == ACTION[2]) {
					addObjectToArray(eliminatedPlayers,userNum);
					eliminatePlayer(userNum);
					logUserAction(PLAYER_NAMES[userNum - 1], "****ing bad hand. Fold!")
				} else if(spanCollection[i].innerHTML == ACTION[1]) {
					makeCall(user, CALL);
					logUserAction(PLAYER_NAMES[userNum - 1], "Khm... let's play. Call!")
				} else if(spanCollection[i].innerHTML == ACTION[0]) {
					makeAllIn(user);
					logUserAction(PLAYER_NAMES[userNum - 1], "Let's risk. All in!")
					addObjectToArray(eliminatedPlayers,userNum);
				}
			} 
		}
	} else {
		eliminatePlayer(userNum);
	}
}

function eliminatePlayer(userNum)
{
	var user = document.getElementById("user-" + userNum);
	var spanCollection = user.getElementsByTagName("b");

	spanCollection[0].className = "c1";
	spanCollection[1].className = "c2";
	
	spanCollection[0].innerHTML = "";
	spanCollection[1].innerHTML = "";
	
	var cardsCollection = user.getElementsByTagName("span");
	for(i = 0; i < cardsCollection.length; i++) {
		if(cardsCollection[i].getAttribute("class") == "cards") {
			cardsCollection[i].setAttribute("class", "c3");
		}
	}
}

function resetActions()
{
	for(i = 1; i <= P_NUM; i++) {
		var user = document.getElementById("user-status-" + i);
		if(user) user.innerHTML  = "";
		
	}
}

function resetChips()
{
	for(i = 1; i <= P_NUM; i++) {
		var chip = document.getElementById("user-bid-" + i);
		if(chip) chip.innerHTML  = "";
		
	}
}

function chooseCardsForUser(userNum)
{
	var user = document.getElementById("user-" + userNum);
	changeTurn(userNum);
	var bCollection = user.getElementsByTagName("b");
	var spanCollection = user.getElementsByTagName("span");
	showCardsForUser(user);
	for (i = 0; i < bCollection.length; i++) {
            if(bCollection[i].getAttribute("class") == "c1" || bCollection[i].getAttribute("class") == "c2") {
				selected = false;
				while(!selected) {
					face = FACES[Math.floor(Math.random() * 13)];
					suit = SUITS[Math.floor(Math.random() * 4)];
					card = face + suit;
					if(!arrayContains(usedCards, card)) {
						bCollection[i].innerHTML = face;
						bCollection[i].className = suit;
						addObjectToArray(usedCards, card);
						selected = true;
					}
				}
				
            } 
    }
	
	for(i = 0; i < spanCollection.length; i++) {
		if(spanCollection[i].getAttribute("class") == "hide") {
			switch(userNum) {
				case playersOrder[0]: 
					spanCollection[i].setAttribute("class", "role dealer");
					spanCollection[i].innerHTML = 'D';
					break;
				case playersOrder[1]: 
					spanCollection[i].setAttribute("class", "role smallblind");
					spanCollection[i].innerHTML = 'SB';
					makeCall(user, SBLIND);
					break;
				case playersOrder[2]: 
					spanCollection[i].setAttribute("class", "role bigblind");
					spanCollection[i].innerHTML = 'BB';
					makeCall(user, BBLIND);
					break;
			}
		}
	}
}

function chooseCardForTable(table, cardNumber)
{
	var liCollection = table.getElementsByTagName("li");
	temp = 0;
        for (i = 0; i < liCollection.length; i++) {
            if(liCollection[i].getAttribute("class") == "card") {
					if(liCollection[i].innerHTML == cardNumber) {
					selected = false;
					while(!selected) {
						faceNum = Math.floor(Math.random() * 13);
						suitNum = Math.floor(Math.random() * 4);
						card = FACES[faceNum] + SUITS[suitNum];
						if(!arrayContains(usedCards, card)) {
							liCollection[i].className = "card-"+TABLE_SUITS[suitNum]+"-"+FACES[faceNum].toLowerCase();
							addObjectToArray(usedCards, card);
							selected = true;
						}
					}
				} 
			
			}
        }
}

function runPreFlop()
{
	logUserAction("System", "Running preflop");
	for(var position in playersOrder) {
		player = playersOrder[position];
		setTimeout('chooseCardsForUser('+ player +')', 2000 * position);
	}
}

function runFlop()
{
	logUserAction("System", "Running flop");
	var element = document.getElementById("table");
	chooseCardForTable(element, 1);
}

function runTurn()
{
	logUserAction("System", "Running turn");
	resetActions();
	resetChips();
	var element = document.getElementById("table");
	chooseCardForTable(element, 2);
}

function runRiver()
{
	logUserAction("System", "Running river");
	resetActions();
	resetChips();
	var element = document.getElementById("table");
	chooseCardForTable(element, 3);
}


function showCardsForUser(user)
{
	var cardsCollection = user.getElementsByTagName("span");
	for(i = 0; i < cardsCollection.length; i++) {
		if(cardsCollection[i].getAttribute("class") == "c3") {
			cardsCollection[i].setAttribute("class", "cards");
		}
	}
}

